import * as vscode from 'vscode';
import { ComponentCompletionProvider } from '@/provider/completion-provider';
import { ComponentLoader } from '@/loader/component-loader';
import StatusBarManager from '@/bar/status-bar';
import { REACT_SELECTORS, REACT_TRIGGER_CHARACTERS, VUE_SELECTORS, VUE_TRIGGER_CHARACTERS } from '@/consts/common';

let componentLoader: ComponentLoader;
let fileWatcher: vscode.FileSystemWatcher;
let completionProvider: ComponentCompletionProvider;
let statusBarManager: StatusBarManager;

// 扩展激活函数，当扩展被激活时调用（通过activationEvents触发）
export async function activate(context: vscode.ExtensionContext) {
    console.log('组件属性补全扩展已激活');

     // 初始化JSON加载器
    componentLoader = new ComponentLoader(context);

    // 创建补全提供程序实例
    completionProvider = new ComponentCompletionProvider();

    // 初始化状态栏管理器
    statusBarManager = new StatusBarManager(context);

   // 注册各种语言的补全提供程序
    const providers = [
        // React JSX/TSX
        vscode.languages.registerCompletionItemProvider(
            REACT_SELECTORS,
            completionProvider,
           ...REACT_TRIGGER_CHARACTERS
        ),
        
        // Vue 模板
        vscode.languages.registerCompletionItemProvider(
            VUE_SELECTORS,
            completionProvider,
            ...VUE_TRIGGER_CHARACTERS
        )
    ];

    // 注册命令
    const commands = [
        // 重新加载配置
        vscode.commands.registerCommand('componentCompletion.reload', async () => {
            await reloadComponentLibraries();
            vscode.window.showInformationMessage('组件配置已重新加载');
        }),

        // 查看已加载组件
        vscode.commands.registerCommand('componentCompletion.list', async () => {
            await listLoadedComponents();
        }),

        // 手动触发补全
        vscode.commands.registerCommand('componentCompletion.triggerCompletion', async () => {
            await vscode.commands.executeCommand('editor.action.triggerSuggest');
            vscode.window.showInformationMessage('已触发组件补全');
        }),

        // 显示命令列表
        vscode.commands.registerCommand('componentCompletion.showCommands', async () => {
            await statusBarManager.showCommands();
        }),

        // 切换状态栏显示
        vscode.commands.registerCommand('componentCompletion.toggleStatusBar', async () => {
            statusBarManager.toggle();
            const status = statusBarManager.getStatus();
            vscode.window.showInformationMessage(`状态栏已${status.isVisible ? '显示' : '隐藏'}`);
        }),

        // 添加组件导入
        // vscode.commands.registerCommand('componentCompletion.addImport', async (componentName: string, importPath: string) => {
        //     await addComponentImport(componentName, importPath);
        // })
    ];

    // 设置文件变化监听
    fileWatcher = componentLoader.setupFileWatcher();

     // 初始加载配置的库
    await initializeComponentLibraries();

    // 更新状态栏信息
    updateStatusBarWithLibraryInfo();

    context.subscriptions.push(
        ...providers,
        ...commands,
        fileWatcher,
        statusBarManager
    );
}

/**
 * 更新状态栏显示库信息
 */
function updateStatusBarWithLibraryInfo(): void {
    const libraries = componentLoader.getLoadedLibraries();
    const componentsCount = componentLoader.getTotalComponentsCount();
    
    // 可以在这里添加自定义命令到状态栏
    statusBarManager.addCommand('componentCompletion.list', `查看组件 (${componentsCount}个)`);
    statusBarManager.addCommand('componentCompletion.reload', `重新加载 (${libraries.length}个库)`);
}

/**
 * 初始化组件库
 */
async function initializeComponentLibraries(): Promise<void> {
    try {
        await componentLoader.loadAllConfiguredLibraries();
        const libraries = componentLoader.getLoadedLibraries();
        const components = componentLoader['dataStore'].getAllComponents();
        
        // Logger.log(`组件库初始化完成: 加载了 ${components.length} 个组件来自 ${libraries.length} 个库`);
        vscode.window.showInformationMessage(`组件补全已就绪: ${components.length} 个组件可用`);
    } catch (error) {
        // Logger.log(`组件库初始化失败: ${error.message}`, 'error');
        vscode.window.showErrorMessage('组件库加载失败，请检查配置');
    }
}

/**
 * 重新加载组件库
 */
async function reloadComponentLibraries(): Promise<void> {
    try {
        await componentLoader.reloadAllLibraries();
        const libraries = componentLoader.getLoadedLibraries();
        const components = componentLoader['dataStore'].getAllComponents();
        
        // Logger.log(`组件库重新加载完成: ${components.length} 个组件来自 ${libraries.length} 个库`);
        
        // 更新状态栏信息
        updateStatusBarWithLibraryInfo();
    } catch (error) {
        // Logger.log(`重新加载组件库失败: ${error.message}`, 'error');
        throw error;
    }
}

/**
 * 列出已加载的组件
 */
async function listLoadedComponents(): Promise<void> {
    const libraries = componentLoader.getLoadedLibraries();
    const components = componentLoader['dataStore'].getAllComponents();
    
    if (components.length === 0) {
        vscode.window.showWarningMessage('没有加载任何组件');
        return;
    }

    const componentList = libraries.map(library => {
        const libComponents = componentLoader['dataStore'].getComponentsByLibrary(library);
        return `📦 ${library} (${libComponents.length}个组件)`;
    }).join('\n');

    vscode.window.showInformationMessage(
        `已加载 ${components.length} 个组件来自 ${libraries.length} 个库`
    );

    // 在输出通道显示详细列表
    const outputChannel = vscode.window.createOutputChannel('组件补全 - 已加载组件');
    outputChannel.appendLine('🚀 已加载的组件库和组件:');
    outputChannel.appendLine('');
    outputChannel.appendLine(componentList);
    outputChannel.appendLine('');
    outputChannel.appendLine(`总计: ${components.length} 个组件来自 ${libraries.length} 个库`);
    outputChannel.show();
}

/**
 * 扩展停用函数
 * 当扩展被停用时调用
 */
export function deactivate() {
    console.log('组件属性补全扩展已停用');
    if (fileWatcher) {
        fileWatcher.dispose();
    }
}